/**
 * Copyright (c) 2018 小润科技 All rights reserved.
 * <p>

 * <p>
 * 版权所有，侵权必究！
 */

package com.xr.sy.modules.security.oauth2;

import com.xr.common.constant.Constant;
import com.xr.common.exception.ErrorCode;
import com.xr.common.utils.ConvertUtils;
import com.xr.common.utils.MessageUtils;
import com.xr.sy.modules.message.entity.SysMailEntity;
import com.xr.sy.modules.message.service.SysMailService;
import com.xr.sy.modules.security.user.UserDetail;
import com.xr.sy.modules.sys.dto.SysUserDTO;
import com.xr.sy.modules.sys.entity.SysUserEntity;
import com.xr.sy.modules.security.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 认证
 */
@Component
public class Oauth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;

    @Autowired
    private SysMailService sysMailService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDetail user = (UserDetail) principals.getPrimaryPrincipal();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(user);
        //permsSet.add("business:message:query");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        UserDetail userDetail = null;
        if (accessToken.equalsIgnoreCase(Constant.TOKEN_TEST_VALUE)) {
            //测试token-超级管理员权限
            SysUserDTO sysUserDTO = new SysUserDTO();
            sysUserDTO.setId(Long.decode("1067246875800000001"));
            //查询用户信息
            SysUserEntity userEntity = new SysUserEntity();
            userEntity.setId(Long.decode("1067246875800000001"));
            userEntity.setUsername("admin");
            userEntity.setRealName("管理员");
            userEntity.setGender(0);
            userEntity.setEmail("root@renren.io");
            userEntity.setMobile("13500000000");
            userEntity.setSuperAdmin(1);
            userEntity.setStatus(1);
            //转换成UserDetail对象
            userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);
            //获取用户对应的部门数据权限
            List<Long> deptIdList = shiroService.getDataScopeList(userDetail.getId());
            userDetail.setDeptIdList(deptIdList);
            //账号锁定
            if (userDetail.getStatus() == 0) {
                throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK));
            }
        } else {
            //根据accessToken，查询用户信息
            SysUserDTO tokenEntity = shiroService.getByToken(accessToken);
            //token失效
            if (tokenEntity == null) {
                throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID));
            }
            String username = tokenEntity.getUsername();
            if(!username.endsWith(".com")){
                //查询用户信息
                SysUserEntity userEntity = shiroService.getUser(tokenEntity.getId());
                //转换成UserDetail对象
                userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);

                //获取用户对应的部门数据权限
                //List<Long> deptIdList = shiroService.getDataScopeList(userDetail.getId());
                //userDetail.setDeptIdList(deptIdList);

                //账号锁定
//            if (userDetail.getStatus() == 0) {
//                throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK));
//            }
            }else {
                SysMailEntity entity = sysMailService.getByMail(username);
                userDetail = new UserDetail();
                userDetail.setUsername(username);
                userDetail.setEmail(entity.getName());
                userDetail.setDeptId(entity.getDeptId());
            }

        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
        return info;
    }

}